package com.team.teamuserservice.service.impl;

import cn.hutool.json.JSONUtil;
import com.team.teamuserservice.entity.dto.DelayRescueMessage;
import com.team.teamuserservice.entity.dto.UserLocation;
import com.team.teamuserservice.entity.po.BizRescueTask;
import com.team.teamuserservice.service.DelayMessageService;
import com.team.teamuserservice.service.IBizRescueTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 延迟消息服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DelayMessageServiceImpl implements DelayMessageService {

    private final RabbitTemplate rabbitTemplate;




    @Override
    public void sendDelayRescueMessage(DelayRescueMessage delayRescueMessage) {


        try {
            String message = JSONUtil.toJsonStr(delayRescueMessage);
            log.info("发送延迟救援消息: {}", message);
            
            // 发送到延迟交换机，设置延迟时间
            rabbitTemplate.convertAndSend(
                "delay.direct", 
                "delay", 
                message,
                msg -> {
                    // 设置消息延迟时间（毫秒）
                    msg.getMessageProperties().setDelay(delayRescueMessage.getDelayTime().intValue());
                    return msg;
                }
            );
            
            log.info("延迟救援消息发送成功，延迟时间: {}ms", delayRescueMessage.getDelayTime());
        } catch (Exception e) {
            log.error("发送延迟救援消息失败", e);
        }
    }

    @Override
    public void send5kmBroadcastMessage(UserLocation userLocation, Long rescueTaskId) {
        //构建延迟消息信息
        DelayRescueMessage delayMessage = new DelayRescueMessage();
        delayMessage.setUserLocation(userLocation);
        delayMessage.setRescueTaskId(rescueTaskId);
        delayMessage.setDelayType(1); // 5km广播
        delayMessage.setCreateTime(System.currentTimeMillis());
        delayMessage.setDelayTime(60000L); // 1分钟后发送
        //发送延迟消息
        sendDelayRescueMessage(delayMessage);
        log.info("已发送5km广播延迟消息，任务ID: {}, 用户ID: {}", rescueTaskId, userLocation.getUserId());
    }

    @Override
    public void send10kmBroadcastMessage(UserLocation userLocation, Long rescueTaskId) {
        //构建延迟消息信息
        DelayRescueMessage delayMessage = new DelayRescueMessage();
        delayMessage.setUserLocation(userLocation);
        delayMessage.setRescueTaskId(rescueTaskId);
        delayMessage.setDelayType(2); // 10km广播
        delayMessage.setCreateTime(System.currentTimeMillis());
        delayMessage.setDelayTime(120000L); // 2分钟后发送
        //发送延迟消息
        sendDelayRescueMessage(delayMessage);
        log.info("已发送10km广播延迟消息，任务ID: {}, 用户ID: {}", rescueTaskId, userLocation.getUserId());
    }
} 